<?php

namespace App\Http\Controllers\Admin;

use App\Models\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class Index extends Controller
{
    //登录
    public function login()
    {
        if (request()->isMethod('post')) {
            $data = request()->only(['username', 'password']);
            $result = (new Admin)->login($data);
            if ($result == 1) {
                $msg = [
                    'code' => 1,
                    'msg' => '登录成功',
                    'url' => url('admin/index')
                ];
            }else {
                $msg = [
                    'code' => 0,
                    'msg' => $result
                ];
            }
            return $msg;
        }
        if (session()->has('admin')) {
            return redirect('admin/index');
        }
        return view('admin.index.login');
    }

    //管理员注册
    public function register()
    {
        if (request()->isMethod('post')) {
            $data = request()->only(['username', 'password', 'conpass', 'nickname', 'email']);
            $result = (new Admin)->register($data);
            if ($result == 1) {
                $msg = [
                    'code' => 1,
                    'msg' => '注册成功',
                    'url' => url('admin')
                ];
            }else {
                $msg = [
                    'code' => 0,
                    'msg' => $result
                ];
            }
            return $msg;
        }
        return view('admin.index.register');
    }

    //忘记密码
    public function forget()
    {
        if (request()->isMethod('post')) {
            $data = request()->only(['email']);
            $result = (new Admin)->getCode($data);
            if ($result == 1) {
                $msg = [
                    'code' => 1,
                    'msg' => '验证码已发往邮箱'
                ];
            }else {
                $msg = [
                    'code' => 0,
                    'msg' => $result
                ];
            }
            return $msg;
        }
        return view('admin.index.forget');
    }

    //重置密码
    public function reset()
    {
        $data = request()->only(['email', 'code']);
        $result = (new Admin)->reset($data);
        if ($result == 1) {
            $msg = [
                'code' => 1,
                'msg' => '重置密码成功，请去邮箱查看',
                'url' => url('admin')
            ];
        }else {
            $msg = [
                'code' => 0,
                'msg' => $result
            ];
        }
        return $msg;
    }
}
